<!--
 * @Description: 
 * @Author: 张文韬
 * @Date: 2024-06-24 15:29:13
 * @LastEditTime: 2024-07-16 14:19:49
 * @LastEditors: 张文韬
 * @Reference: 
-->
<template>
  <e-form
    ref="dialogForm"
    :form-options="formOptions"
    :form-label-width="editFormLabelWidth"
    :form-rules="editFormRules"
    :form-data-current="infoForm"
    @day-change="handleDayChange"
    @start-change="handleStartChange"
    @end-change="handleEndChange"
    @time-change="handleTimeChange"
    @product-change="handleProductChange"
  >
    <template #dest>
      <el-button type="primary" v-auth="'policy_manage_address'" :icon="Edit" @click="showDestSelect" text>常用目的地</el-button>
    </template>
    <template #notice>
      <ul class="w-100% p-10px pl-20px border-1 border-gray-200 b-rd-5px">
        <!-- <div v-html="formData.selectProduct?.agreeText"></div> -->
        <li class="list-disc-inside line-height-25px" v-for="t in noticeContent">{{ t }}</li>
      </ul>
    </template>
  </e-form>
  <el-dialog
    v-model="dialogShow"
    title="目的地管理"
    :width="800"
    :before-close="closeDialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false">
    <Destination v-if="dialogShow" :data="formData.addresses" @update="getDestData" />
  </el-dialog>
</template>

<script setup>

import eForm from '@/components/e-form';
import Destination from '../Destination/index.vue'
import { editFormOptions, editFormRules } from './config';
import { dayjs } from 'element-plus';
import { Edit } from '@element-plus/icons-vue'
import { destination, productList, searchByMuenIdAndDate } from '@/api/insurance';
import { bbAddress } from '@/api/insurance'
import { useRoute } from 'vue-router'

let defaultDay = 6
let defaultStartTime = '00:00:00'
let startDateTime = ''
let endDateTime = ''

const props = defineProps({
  loading: {
    type: Boolean,
    default: false
  },
  dataSource: {
    type: Object,
    default: () => {}
  },
})

const emits = defineEmits(['updateProduct', 'priceChange'])

// const userStore = useUserStore()
// const { user } = storeToRefs(userStore)

const route = useRoute()

const formData = reactive({
  selectProduct: {},
  products: [],
  addresses: []
})

// 编辑表单
const dialogForm = ref(null)
const formOptions = reactive(editFormOptions)
// 初始化获取下拉项
const loadData = async () => {
  const { data } = await productList()  
  data.map(o => {
    o.menuEntityList.map(p => {
      formData.products.push({
        ...o,
        ...p,
        code: p.code,
        label: p.showName,
        value: {...o, ...p, code: p.code}
      })
    })
  })
  const { data: { records: addresses } } = await bbAddress({
    current: 1,
    size: 999
  })
  formData.addresses = addresses.map(o => ({
    ...o,
    label: o.name,
    value: o
  }))
  formOptions.forEach(o => {
    if (o.key == 'product') {
      o.options = formData.products
    } else if (o.key == 'addressInfo') {
      o.options = formData.addresses
    }  else if (o.key == 'insuranceEndDate') {
      o.props.disabledDate = (time) => {
        if (!dialogForm.value) return true
        const formData = dialogForm.value.formData
        if (formData.insuranceBeginDate && formData.insuranceBeginDate.length > 0) {
          return time.getTime() <= dayjs(formData.insuranceBeginDate).valueOf()
        }
        return true
      }
    }
  })
}
loadData()

const editFormLabelWidth = '100px'
const infoForm = reactive({
  // product_id: '',
  insurancePeriod: defaultDay,
  unitPrice: 0,
  discountPrice: 0
})

const noticeContent = ref(['请先选择保险产品'])

const handleDayChange = async (dateNum) => {
  const formData = dialogForm.value.formData
  if (dateNum > 366) {
    formData.insurancePeriod = 366
  }
  if (formData.insuranceBeginDate && formData.insuranceBeginDate.length > 0) {
    endDateTime = dayjs(`${formData.insuranceBeginDate} ${defaultStartTime}`).add(dateNum, 'day').subtract(1,'s').format('YYYY-MM-DD HH:mm:ss')
    formData.insuranceEndDate = endDateTime
  }
  setPayment()
}

const handleStartChange = (val) => {
  const formData = dialogForm.value.formData
  formData.startTime = defaultStartTime
  startDateTime = `${val} ${defaultStartTime}`
  endDateTime = dayjs(startDateTime).add(formData.insurancePeriod, 'day').subtract(1,'s').format('YYYY-MM-DD HH:mm:ss')
  formData.insuranceEndDate = endDateTime
}

const handleEndChange = (val) => {
  const formData = dialogForm.value.formData
  const time = endDateTime.split(' ')[1]
  endDateTime = val.split(' ')[0] + ' ' + time
  formData.insuranceEndDate = endDateTime
  if (formData.insuranceBeginDate && formData.insuranceBeginDate.length > 0) {
    formData.insurancePeriod = dayjs(endDateTime).add(1, 's').diff(formData.insuranceBeginDate, 'day')
  }
}

const handleTimeChange = (val) => {
  const formData = dialogForm.value.formData
  defaultStartTime = val
  handleStartChange(formData.insuranceBeginDate)
}

const handleProductChange = (value) => {
  formData.selectProduct = value
  infoForm.insurancePeriod = value.fixedTerm || defaultDay
  infoForm.unitPrice = value.price
  noticeContent.value = value?.agreeText.split('\n').map(t => t.trim())
  formOptions.forEach(o => {
    if (o.key == 'insurancePeriod') {
      o.props.disabled = !!value.fixedTerm
    }
    else if (o.key == 'insuranceEndDate') {
      o.props.disabled = !!value.fixedTerm
    }
  })
  emits('updateProduct', value)
  setPayment()
}

const setPayment = async (row) => {
  if (!infoForm.insurancePeriod || !formData.selectProduct) return
  const { data: { price, discountPrice } } = await searchByMuenIdAndDate({
    productMenuId: formData.selectProduct?.id,
    dateNum: infoForm.insurancePeriod
  })
  infoForm.unitPrice = price
  infoForm.discountPrice = discountPrice
  emits('priceChange', discountPrice)
}

const dialogShow = ref(false)
const showDestSelect = () => {
  openDialog()
}
const openDialog = () => {
  // dialogType.value = type
  dialogShow.value = true
}

const closeDialog = () => {
  dialogShow.value = false
}

const destData = ref([])
const getDestData = async() => {
  const { data: { records: addresses } } = await bbAddress()
  formData.addresses = addresses
  const column = formOptions.find(o => o.key == 'addressInfo')
  column.options = addresses.map(o => ({
    ...o,
    label: o.name,
    value: o
  }))
}

const getData = async() => {
  const result = await dialogForm.value.handleValidate()
  const product = { 
    ...formData.selectProduct, 
    productMenuId: formData.selectProduct.id, 
    productMenuCode: formData.selectProduct.code 
  }
  delete product.id
  if (result) {
    return  {
      ...dialogForm.value.formData,
      ...product,
      // id: formData.selectProduct.productId,
      insuranceBeginDate: `${dialogForm.value.formData.insuranceBeginDate} ${dialogForm.value.formData.startTime}`,
      // productId: formData.selectProduct.id,
      renewalType: '0',
      addressName: dialogForm.value.formData.addressInfo.map(o => o.name).join(','),
      addressId: dialogForm.value.formData.addressInfo.map(o => o.id).join(','),
      addressEgName:  dialogForm.value.formData.addressInfo.map(o => o.egName).join(','),
    }
  }
  return
}

watch(() => formData.products, (val) => {
  if (!val || val.length == 0 || !props.dataSource?.productId) {
    return
  }
  const product = formData.products.find(o => o.id == props.dataSource.productMenuId || o.code == props.dataSource.productMenuCode)
  if (product) {
    infoForm.product = product
    handleProductChange(product)
  }
  for (const key in props.dataSource) {
    infoForm[key] = props.dataSource[key]
  }
  const dateTime = props.dataSource.insuranceBeginDate?.split(' ')||[]
  infoForm.insuranceBeginDate = dateTime[0]
  infoForm.startTime = dateTime[1]
  const addressNames = props.dataSource.addressName?.split(',')||[]
  const addressEgNames = props.dataSource.addressEgName?.split(',')||[]
  infoForm.addressInfo = `${props.dataSource.addressId}`.split(',').map((o, i) => ({ id: o, name: addressNames[i], egName: addressEgNames[i] }))
}, { immediate:true,deep: true })

defineExpose({
  getData
})

</script>